//多条数据的遍历
function numberTravel(data){
	var str = '';
	for(var x in data){
		var row = data[x];
		str += singleTravel(row);
	}
	return str;
}


//单条数据的遍历
function singleTravel(row){
	var str ='<tr>'+
			'<td id="title"><input type="text" value="'+row.title+'" /></td>'+
			'<td id="content"><input type="text" value="'+row.content+'" /></td>'+
			'<td>'+row.user_id+'</td>'+
			'<td>'+row.create_time+'</td>'+
			'<td><input type="button" onclick=edit(this) data-id="'+row.id+'" value="修改" />'+
			'<input type="button" onclick=del(this) data-id="'+row.id+'" value="删除" /></td>'+
			'<tr>';
	return str;
 }


//贴子详情函数
function getPostDetail(id, cur){
	$.get('/index/index/postDetail',{id:id,page:cur}, function(postDetail){
		var str = numberTravel(postDetail.data);
		$("#post-detail-tab").append(str);
		total = postDetail.total;
		per_page = postDetail.per_page;
		pageCount = Math.ceil(total/per_page);
		lastPageCount = total-(pageCount-1)*per_page;
		console.log(lastPageCount);
		page(pageCount,$('#pageIt'));
	},'json');
}

$(document).ready(function(){
	//获取从贴子列表传过来的id
	var a = location.search.split('=');
	var detailId = a[1];
	//贴子详情函数
	getPostDetail(detailId, 1);
	
	//分页事件
	$('#pageIt').on('click', 'a', function(){
		currentPage = $(this).attr("pagenum");
		console.log(currentPage);
		$.get('/index/index/postDetail',{page:currentPage, id:detailId},function(postDetail){
			var str = numberTravel(postDetail.data);
			$('#post-detail-tab tr:not(#headq)').remove();
			$('#post-detail-tab').append(str);
		});
	});
	
    //贴子回复事件
	$('#reply').click(function(){
		var content = $(this).prev('#text').val();
		$.post('/index/index/postReply',{content:content, id:detailId},function(d){
			if(d.error==0){
				var str = singleTravel(d.postReply);
				$('#post-detail-tab').append(str);
				$('#info').text(d.info);
			}else{
				$('#info').text(d.info);
			}
		});
	});
});


//贴子编辑事件
var edit = function(node){
	var title = $(node).parent().prevAll('#title').children().val();
	var content = $(node).parent().prevAll('#content').children().val();
    var id = $(node).attr('data-id');
	$.post('/index/index/postEdit',{title:title,content:content,id:id},function(postEdit){
		$('#info').text(postEdit.info);
	});
}


//帖子删除事件
var del = function(node){
    var id = $(node).attr('data-id');
    if(confirm("您是否确定要删除这个帖子,删除后无法恢复哟!")){
    	$.post('/index/index/postDelete',{id:id},function(postDelete){
    			if(postDelete.error==0){
    				$(node).parent().parent().remove();
    				$('#info').text(postDelete.info);
    			}
    			if(postDelete.error==1){
    				$('#info').text(postDelete.info);	
    			}
	            if(postDelete.error==2){
	            	$('#info').text(postDelete.info);	
		            window.location.href = 'postList.html';
	            }
    		});
    }
}
